<?php

namespace App\Http\Controllers\H5;

use App\Excels\Exports\ProjectMallDetailExport;
use App\Excels\Exports\ProjectMallExport;
use App\Http\Controllers\Admin\BackMoneyCountController;
use App\Http\Controllers\Controller;
use App\Models\Account;
use App\Models\Mall;
use App\Models\MallDateFinance;
use App\Models\ProjectMall;
use App\Models\ProjectMallCapital;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class ProjectMallController extends Controller
{

    public function malls(Request $request){
        $userInfo = $request->offsetGet("userInfo");
        $malls = ProjectMall::query()
            ->from("project_mall_capital as a")
            ->join("project_mall as b","a.p_mall_id","b.id")
            ->join("mall as c","b.merchant_no","c.merchant_no")
            ->when($userInfo->is_show == 1, function (Builder $query)use($userInfo) {
                $query->where("a.capital_id",$userInfo->id);
            })
            ->where("b.status",1)
            ->groupBy("a.p_mall_id")
            ->select("b.id","c.name")
            ->orderByDesc("b.project_id")
            ->orderByDesc("b.id")
            ->get();
        return $this->httpSuccess($malls);
    }


    public function index(Request $request){
        $account = Account::query()->find(1);
        $userInfo = $request->offsetGet("userInfo");
        $mallName = $request->input("mallName","");
        $incomStatus = $request->input("incomStatus","");
        $download = $request->input("download","");
        $malls = ProjectMall::query()
            ->with([
                "mall",
            ])
            ->from("project_mall_capital as a")
            ->join("project_mall as b","a.p_mall_id","b.id")
            ->join("mall as c","b.merchant_no","c.merchant_no")
            ->when($userInfo->is_show == 1, function (Builder $query)use($userInfo) {
                $query->where("a.capital_id",$userInfo->id);
            })
            ->where("b.status",1)
            ->when($mallName, function (Builder $query)use($mallName) {
                $query->where("c.name","like","%$mallName%");
            })
            ->when(is_numeric($incomStatus), function (Builder $query)use($incomStatus) {
                $query->where("b.incom_status","like",$incomStatus);
            })
            ->groupBy("a.p_mall_id")
            ->select("b.*","c.sub_date","a.money as my_money")
            ->orderByDesc("b.project_id")
            ->orderByDesc("b.id")
            ->get();
        $allMallDatas = [
            "mallNames"=>[],
            "backMoney"=>0,
            "backRate"=>0,
            "incomeRate"=>0,
            "incomeMoney"=>0,
            "money"=>0,
            "alleMoney"=>0,
            "backMoneyPerDay"=>0,
            "backDate"=>"",
            "dates"=>[],
            "my"=>[
                "isShow"=>false,
                "backMoney"=>0,
                "money"=>0,
                "allMoney"=>0,
                "rate"=>0,
            ]
        ];
        $loginAccounts = [];
        $accounts = Account::query()->get();
        foreach ($accounts as $acc){
            $loginAccounts[] = [
                "isLogin"=>$acc->login_status == 1,
                "syncAt"=>$acc->sync_at,
                "plamtName"=>$acc->plamt_name,
            ];
        }
        if(!$malls->count()){
            if($download){
                $export = new ProjectMallExport([],false);
                $fileName = uniqid() .'-'.date("Y-m-d_H:i:s").'.xlsx';
                Excel::store($export , 'public/files/'.$fileName);
                $url = "/storage/files/".$fileName;
                return $this->httpSuccess([
                    "fileUrl"=>$url
                ]);
            }else{
                return $this->httpSuccess([
                    "mallData"=>[],
                    "allMallDatas"=>$allMallDatas,
                    "loginInfo"=>$loginAccounts
                ]);
            }
        }
        $merchantNos = $malls->pluck("merchant_no")->toArray();
        $finances = MallDateFinance::query()
            ->whereIn("merchant_no",$merchantNos)
            ->selectRaw("merchant_no,sum(income) as income,sum(settle_money) as settle_money,count(*) as days")
            ->groupBy("merchant_no")
            ->get();

        foreach ($malls as $mall){
            $uxdate = empty($mall->end_back_date_time) ? date("Y-m-d") : $mall->end_back_date_time;
            $mall->all_end_back_date = null;
            $mall->my_end_back_date = null;
            $mall->back_money = 0; //回款金额
            $mall->back_rate = 0; //回款比例
            $mall->order_money = 0; //营业额
            $mall->incom_money = 0; //收益金额
            $mall->back_date = ""; //回本日期
            $mall->my_back_money_rate = 0;
            $mall->my_incom_money = 0;
            $mall->back_money_per_day = 0; //平均每日回款
            $mall->all_money = round($mall->money * (1 + $mall->income_rate / 100),2); //应收总额
            $mall->all_money = number_format($mall->all_money,2,".","");
            $finance = $finances->where("merchant_no",$mall->merchant_no)->first();
            $mall->back_day_num = 0;
            $mall->my_back_money = 0;
            $mall->my_money_rate = round($mall->my_money / $mall->money,4);
            $mall->my_all_money = round($mall->my_money * (1 + $mall->income_rate / 100),2);
            $mall->begin_date = date("Y.m.d",strtotime($mall->mall->sub_date));
            $mall->begin_date_day_num = ceil((strtotime($uxdate) - strtotime($mall->mall->sub_date)) / 86400);

            if(!empty($finance)){
                $mall->back_money = $finance->settle_money;
                $mall->order_money = $finance->income;
                $mall->back_rate = round(($mall->back_money / $mall->money) * 100,2);
                $mall->incom_money = $mall->back_money - $mall->money;
                $mall->incom_money = round($mall->incom_money,2);
                $mall->incom_money <= 0 and $mall->incom_money = 0;
                $mall->back_money_per_day = round($mall->back_money / $finance->days,2);
                if($mall->back_money_per_day > 0){
                    $backDayNum = ceil($mall->money / $mall->back_money_per_day);
                    //$mall->back_day_num = $backDayNum;
                    $mall->back_date = date("Y-m-d",strtotime(date("Y-m-d",strtotime($mall->sub_date))) + $backDayNum * 86400);
                    $mall->back_day_num = ceil((strtotime($mall->back_date) - strtotime($uxdate)) / 86400);
                }

                if($userInfo->is_show == 1){
                    $mall->my_back_money = round($mall->back_money * $mall->my_money_rate,2);
                    $mall->my_back_money_rate = round($mall->my_back_money / $mall->my_money,4);
                    $mall->my_incom_money = round($mall->incom_money * $mall->my_money_rate,2);

                }
            }
            $mall->my_money_rate = round($mall->my_money_rate * 100,2);
            $mall->my_back_money_rate = round($mall->my_back_money_rate * 100,2);
            $allMallDatas["my"]["money"] += round($mall->my_money,2);
            $allMallDatas["my"]["allMoney"] += round($mall->my_all_money,2);
            $allMallDatas["my"]["backMoney"] += $mall->my_back_money;
            $allMallDatas["mallNames"][] = [
                "mallName"=>$mall->mall->name,
                "incomStatus"=>$mall->incom_status,
            ];
            $allMallDatas["money"] += $mall->money;
            $allMallDatas["backMoney"] += $mall->back_money;


            $allMallDatas["incomeMoney"] += $mall->incom_money;
            $allMallDatas["alleMoney"] += $mall->all_money;
            $allMallDatas["backMoneyPerDay"] += $mall->back_money_per_day;
            $allMallDatas["backRate"] = round(($allMallDatas["backMoney"] / $allMallDatas["money"]) * 100,2);
            $allMallDatas["dates"][] = strtotime(date("Y-m-d",strtotime($mall->sub_date)));

            $allMallDatas["incomeRate"] += $mall->income_rate;

            if($userInfo->is_show == 1 && $mall->my_back_money > 0 && $mall->show_date && $mall->end_back_date > 0){
                $udate = (
                    (strtotime($uxdate) - strtotime($mall->show_date)) / 86400
                ) / 30 / $mall->end_back_date;
                $rudate = round($mall->my_back_money_rate / 100,4);
                $mall->my_end_back_date = round($rudate / $udate,2);
                $mall->my_end_back_date = number_format($mall->my_end_back_date,2,".","");
            }

            if($mall->back_money > 0 && $mall->show_date && $mall->end_back_date > 0){
                $udate = (
                        (strtotime($uxdate) - strtotime($mall->show_date)) / 86400
                    ) / 30 / $mall->end_back_date;
                $rudate = round($mall->back_rate / 100,4);
                $mall->all_end_back_date = round($rudate / $udate,4);
                $mall->all_end_back_date = number_format($mall->all_end_back_date,4,".","");
            }

        }
        $allMallDatas["backMoney"] = number_format($allMallDatas["backMoney"],2,".","");
        $allMallDatas["incomeMoney"] = number_format($allMallDatas["incomeMoney"],2,".","");
        $allMallDatas["alleMoney"] = number_format($allMallDatas["alleMoney"],2,".","");
        $allMallDatas["money"] = number_format($allMallDatas["money"],2,".","");
        $allMallDatas["dates"] = min($allMallDatas["dates"]);
        $allMallDatas["backDayNum"] = $allMallDatas["backMoneyPerDay"] > 0 ? ceil($allMallDatas["money"] / $allMallDatas["backMoneyPerDay"]) : 0;
        $allMallDatas["backDate"] = $allMallDatas["backDayNum"] > 0
            ? date("Y-m-d",$allMallDatas["dates"] + $allMallDatas["backDayNum"] * 86400) : "";
        $allMallDatas["incomeRate"] = round($allMallDatas["incomeRate"] / count($allMallDatas["mallNames"]),2);
        if($userInfo->is_show == 1){
            $allMallDatas["my"]["isShow"] = true;

        }
        $allMallDatas["my"]["rate"] = round($allMallDatas["my"]["money"] / $allMallDatas["money"] * 100,2);
        $allMallDatas["my"]["backMoney"] = round($allMallDatas["my"]["backMoney"],2);
        $allMallDatas["my"]["backMoneyRate"] = round($allMallDatas["my"]["backMoney"] / $allMallDatas["my"]["money"] * 100,2);

        if($download){
            $export = new ProjectMallExport($malls,$userInfo->is_show == 1);
            $fileName = uniqid() .'-'.date("Y-m-d_H:i:s").'.xlsx';
            Excel::store($export , 'public/files/'.$fileName);
            $url = "/storage/files/".$fileName;
            return $this->httpSuccess([
                "fileUrl"=>$url
            ]);
        }else{
            return $this->httpSuccess([
                "mallData"=>$malls,
                "allMallDatas"=>$allMallDatas,
                "loginInfo"=>$loginAccounts
            ]);
        }


    }

    public function dateDetails(Request $request)
    {
        $userInfo = $request->offsetGet("userInfo");
        $account = Account::query()->find(1);
        $mallId = $request->input("mallId","");
        $mall = ProjectMall::query()
            ->with([
                "capitalRel"=>function ($query)use($userInfo) {
                    $query->when($userInfo->is_show == 1, function (Builder $query)use($userInfo) {
                        $query->where("capital_id",$userInfo->id);
                    });
                },
                "mall.mapping.account"
            ])
            ->find($mallId);
        $uxdate = empty($mall->end_back_date_time) ? date("Y-m-d") : $mall->end_back_date_time;
        $pageSize = $request->input("pageSize",20);
        $page = $request->input("page",1);
        $date = $request->input("date","");
        $dateLeft = $request->input("dateLeft","");
        $dateRight = $request->input("dateRight","");
        $download = $request->input("download","");
        if($download){
            $items = MallDateFinance::query()
                ->where("merchant_no",$mall->merchant_no)
                ->when($date, function (Builder $query)use($date) {
                    $query->where("date",$date);
                })
                ->when($dateLeft, function (Builder $query)use($dateLeft) {
                    $query->where("date",">=",$dateLeft);
                })
                ->when($dateRight, function (Builder $query)use($dateRight) {
                    $query->where("date","<=",$dateRight);
                })
                ->orderByDesc("date")
                ->get();
        }else{
            $paginate = MallDateFinance::query()
                ->where("merchant_no",$mall->merchant_no)
                ->when($date, function (Builder $query)use($date) {
                    $query->where("date",$date);
                })
                ->when($dateLeft, function (Builder $query)use($dateLeft) {
                    $query->where("date",">=",$dateLeft);
                })
                ->when($dateRight, function (Builder $query)use($dateRight) {
                    $query->where("date","<=",$dateRight);
                })
                ->orderByDesc("date")
                ->paginate($pageSize,['*'],'page',$page);
            $items = $paginate->items();
        }
        $myMoney = $userInfo->is_show ? $mall->capitalRel[0]->money : 0;
        $rate = round($myMoney / $mall->money,4);
        $loginInfo = [];
        if(!empty($mall->mall->mapping)){
            $loginInfo = [
                "isLogin"=>$mall->mall->mapping->account->login_status == 1,
                "syncAt"=>$mall->mall->mapping->account->sync_at,
                "plamtName"=>$mall->mall->mapping->account->plamt_name,
            ];
        }
        $datas = [
            "mallInfo"=>[
                "mallName"=>$mall->mall->name,
                "mallId"=>$mall->id
            ],
            "dateDatas"=>[],
            "loginInfo"=>$loginInfo,
            "my"=>[
                "isShow"=>$userInfo->is_show == 1,
                "backMoney"=>0,
                "allMoney"=>round($myMoney * (1 + ($mall->income_rate / 100)),2),
                "money"=>round($myMoney,2),
                "rate"=>round($rate * 100,2),
            ],
            "counts"=>[
                "income_money"=>0, //收益金额
                "back_money"=>0, //回款金额
                "back_rate"=>0, //回款比例
                "back_diff_money"=>0, //差异总额
                "money"=>$mall->money,
                "total_money"=>round($mall->money * (1 + ($mall->income_rate / 100)),2),
                "income_rate"=>$mall->income_rate,
                "incom_status"=>$mall->incom_status,
                "sub_account_rate"=>$mall->sub_account_rate,
                "back_date"=>"",
                "begin_date"=>date("Y.m.d",strtotime($mall->mall->sub_date)),
                "begin_date_day_num"=>ceil((strtotime($uxdate) - strtotime($mall->mall->sub_date)) / 86400),
            ]
        ];

        foreach ($items as $item){
            $income = $item->income;
            $backMoney = $item->settle_money;
            $expectedMoney = round($income * ($mall->sub_account_rate / 100),2);
            $backDiffMoney = round($expectedMoney - $backMoney,2);
            $myBackMoney = round($backMoney * $rate , 2);
            $myExpectedMoney = round($expectedMoney * $rate , 2);
            $myBackDiffMoney = round($backDiffMoney * $rate , 2);
            //$datas["my"]["backMoney"] += $myBackMoney;
            $datas["dateDatas"][] = [
                "income"=>$income,
                "expected_money"=>$expectedMoney,
                "back_money"=>$backMoney,
                "back_diff_money"=>$backDiffMoney,
                "date"=>date("Y.m.d",strtotime($item->date)),
                "myBackMoney"=>$myBackMoney,
                "myExpectedMoney"=>$myExpectedMoney,
                "myBackDiffMoney"=>$myBackDiffMoney,
                "back_day_num"=>"",
            ];
        }
        $finance = MallDateFinance::query()
            ->where("merchant_no",$mall->merchant_no)
            //->where("date","<",date("Y-m-d"))
            ->selectRaw("merchant_no,sum(income) as income,sum(settle_money) as settle_money,count(*) as days,merchant_no")
            ->first();
        if(!empty($finance)){
            $datas["counts"]["back_money"] = $finance->settle_money;
            $datas["counts"]["income_money"] = $finance->settle_money - $datas["counts"]["money"] <= 0 ? 0 : round($finance->settle_money - $datas["counts"]["money"],2);
            $datas["counts"]["back_rate"] = round($datas["counts"]["back_money"] / $datas["counts"]["money"] * 100,2);
            $expectedMoney = round($finance->income * ($mall->sub_account_rate / 100),2);
            $datas["counts"]["back_diff_money"] = round($expectedMoney - $datas["counts"]["back_money"],2);
            $backDayNum = ceil($datas["counts"]["back_money"] / $finance->days);
            if($backDayNum > 0){
                $backDayNum = ceil($datas["counts"]["money"] / $backDayNum);
                $datas["counts"]["back_date"] = date("Y-m-d",strtotime(date("Y-m-d",strtotime($mall->mall->sub_date))) + 86400 * $backDayNum);
                $datas["counts"]["back_day_num"] = ceil((strtotime($datas["counts"]["back_date"]) - strtotime($uxdate)) / 86400);
            }
            $datas["my"]["backMoney"] = round($datas["counts"]["back_money"] * $rate,2);
        }

        if($download){
            $export = new ProjectMallDetailExport($datas["dateDatas"],$userInfo->is_show == 1);
            $fileName = uniqid() .'-'.date("Y-m-d_H:i:s").'.xlsx';
            Excel::store($export , 'public/files/'.$fileName);
            $url = "/storage/files/".$fileName;
            return $this->httpSuccess([
                "fileUrl"=>$url
            ]);
        }else{
            return $this->httpSuccess([
                "total"=>$paginate->total(),
                "items"=>$datas
            ]);
        }

    }

    public function countsItems(Request $request){
        $controller = new BackMoneyCountController();
        $input = $request->input();
        $userInfo = $request->offsetGet("userInfo");
        if($userInfo->is_show == 1){
            $input["capitalId"] = $userInfo->id;
        }
        $datas = $controller->mainQuery($input);
        return $this->httpSuccess($datas);
    }
}
